import json
import time
import uuid
import requests
from lib.config import config
from lib.utils import get_logger
from volcenginesdkarkruntime import Ark
import subprocess
import os

logger = get_logger(__name__)

api_key = config.ark_api_key
model = "deepseek-r1-distill-qwen-7b-250120"

appid = config.volc_appid
token = config.volc_token

client = Ark(
    api_key=api_key,
)


def video_to_audio(video_path):
    logger.info(f"开始转换视频为音频,视频路径是{video_path}")
    video_dir = os.path.dirname(video_path)
    video_name = os.path.basename(video_path)
    video_name = video_name.split(".")[0]
    audio_path = os.path.join(video_dir, f"{video_name}.mp3")
    subprocess.run(
        ["ffmpeg", "-i", video_path, "-vn", "-acodec", "libmp3lame", audio_path]
    )
    logger.info(f"转换完成,音频路径是{audio_path}")
    return audio_path


def douyin_to_xhs_text(text):
    # 创建一个对话请求
    completion = client.chat.completions.create(
        model=model,
        messages=[
            {
                "role": "user",
                "content": f"请根据下面内容生成小红书的正文，不超过1000字：{text}",
            },
        ],
    )

    xhs_content = completion.choices[0].message.content

    logger.info(f"小红书正文是{xhs_content}")

    # 生成标题
    completion = client.chat.completions.create(
        model=model,
        messages=[
            {
                "role": "user",
                "content": f"请根据以下小红书正文生成一个不超过20字的爆款标题：{xhs_content}",
            },
        ],
    )
    xhs_title = completion.choices[0].message.content.strip()

    logger.info(f"小红书标题是{xhs_title}")

    completion = client.chat.completions.create(
        model=model,
        messages=[
            {
                "role": "user",
                "content": f"请根据以下小红书正文生成10个相关标签，标签用逗号分隔，每个标签不超过10字：{xhs_content}",
            },
        ],
    )

    xhs_tags = completion.choices[0].message.content

    logger.info(f"小红书标签是{xhs_tags}")
    return xhs_content, xhs_title, xhs_tags


def submit_task(file_url):

    submit_url = "https://openspeech.bytedance.com/api/v3/auc/bigmodel/submit"

    task_id = str(uuid.uuid4())

    headers = {
        "X-Api-App-Key": appid,
        "X-Api-Access-Key": token,
        "X-Api-Resource-Id": "volc.bigasr.auc",
        "X-Api-Request-Id": task_id,
        "X-Api-Sequence": "-1",
    }

    request = {
        "user": {"uid": "fake_uid"},
        "audio": {
            "url": file_url,
            "format": "mp3",
            "codec": "raw",
            "rate": 16000,
            "bits": 16,
            "channel": 1,
        },
        "request": {
            "model_name": "bigmodel",
            "show_utterances": True,
            "corpus": {
                "correct_table_name": "",
                "context": "",
            },
        },
    }
    print(f"Submit task id: {task_id}")
    response = requests.post(submit_url, data=json.dumps(request), headers=headers)
    if (
        "X-Api-Status-Code" in response.headers
        and response.headers["X-Api-Status-Code"] == "20000000"
    ):
        print(
            f'Submit task response header X-Api-Status-Code: {response.headers["X-Api-Status-Code"]}'
        )
        print(
            f'Submit task response header X-Api-Message: {response.headers["X-Api-Message"]}'
        )
        x_tt_logid = response.headers.get("X-Tt-Logid", "")
        print(
            f'Submit task response header X-Tt-Logid: {response.headers["X-Tt-Logid"]}\n'
        )
        return task_id, x_tt_logid
    else:
        print(f"Submit task failed and the response headers are: {response.headers}")
        exit(1)
    return task_id


def query_task(task_id, x_tt_logid):
    query_url = "https://openspeech.bytedance.com/api/v3/auc/bigmodel/query"

    headers = {
        "X-Api-App-Key": appid,
        "X-Api-Access-Key": token,
        "X-Api-Resource-Id": "volc.bigasr.auc",
        "X-Api-Request-Id": task_id,
        "X-Tt-Logid": x_tt_logid,  # 固定传递 x-tt-logid
    }

    response = requests.post(query_url, json.dumps({}), headers=headers)

    if "X-Api-Status-Code" in response.headers:
        print(
            f'Query task response header X-Api-Status-Code: {response.headers["X-Api-Status-Code"]}'
        )
        print(
            f'Query task response header X-Api-Message: {response.headers["X-Api-Message"]}'
        )
        print(
            f'Query task response header X-Tt-Logid: {response.headers["X-Tt-Logid"]}\n'
        )
    else:
        print(f"Query task failed and the response headers are: {response.headers}")
        exit(1)
    return response


def audio_to_text(audio_path):
    logger.info(f"开始转换音频为文本,音频路径是{audio_path}")
    task_id, x_tt_logid = submit_task(audio_path)
    while True:
        query_response = query_task(task_id, x_tt_logid)
        code = query_response.headers.get("X-Api-Status-Code", "")
        if code == "20000000":  # task finished
            res = query_response.json()
            print("SUCCESS!")
            return res.get("result", {}).get("text", "")
        elif code != "20000001" and code != "20000002":  # task failed
            print("FAILED!")
            exit(1)
        time.sleep(1)
